package task04;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static User admin = new User ("admin", "123456");

    public static void main(String[] args){
        ServerSocket listenSocket=null;
        try {
            int serverPort = 8888;
            listenSocket =new ServerSocket(serverPort);
            System.out.println("==========服务器启动==========");

            // 记录连接个数，不断等待客户连接
            int i = 0; // 记录连接个数
            while(true){
                System.out.println("正在监听连接...");
                Socket clientSocket = listenSocket.accept();
                i++;
                System.out.println("建立新连接，总客户连接数：" + i );
                Connection c = new Connection(clientSocket);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != listenSocket) {
                try {
                    listenSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

class Connection extends Thread{
    ObjectOutputStream out;
    ObjectInputStream  in;
    Socket clientSocket;

    public Connection(Socket clientSocket) {
        this.clientSocket = clientSocket;
        this.start();
    }

    public void run(){
        try {
            // 建立io流与socket连接
            in = new ObjectInputStream(clientSocket.getInputStream());
            out = new ObjectOutputStream(clientSocket.getOutputStream());
            // 从socket中读取客户输入并且转换为对象
            System.out.println("正在读取客户端输入...");
            Object o = in.readObject();
            UserMessage msg=(UserMessage)o;
            User user = msg.getUser();
            //判断
            if ( Server.admin.equals(user)){
                msg.setType("success");
                System.out.print("客户身份验证成功");
            }else {
                msg.setType("fail");
                System.out.print("客户身份验证失败");
            }
            out.writeObject(msg);
            System.out.println("\t向客户端回复数据！");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
              e.printStackTrace();
          } finally{
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
